<?php

namespace App\Http\Controllers\Company;

use App\Facades\Style;
use App\Models\Common\CollArea;
use App\Models\Common\CollOption;
use App\Models\Common\English\EnCollArea;
use App\Models\Common\English\EnCollOption;
use App\Models\Company\BuyResume;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyJob;
use App\Models\Company\CompanyUser;
use App\Models\Company\ResumeFavorite;
use App\Models\Personal\Resume;
use App\Models\Personal\ResumeSend;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Config;

class ResumeController extends CommonController
{

    /**
     * 收到应聘简历
     * @param Request $request
     * @return mixed
     */
    public function message(Request $request)
    {
        $user = auth()->guard('company')->user();
        //获取收到应聘简历
        $relist = DB::table('resume_send as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->join('company_job as t2', 'log.job_id', '=', 't2.id')
            ->select(
                'log.id', 'log.status', 'log.created_at', 't1.name', 't1.sex', 't1.birthday',
                't1.education', 't1.homeaddress', 't1.language', 't2.job_title', 'log.resume_id', 'log.job_id', 't2.lang_type'
            )
            ->where('log.company_uid', $user->uid)
            ->where(function ($query) use ($request) {
                if (strlen($request->keyWord) > 0) {
                    $query->where('t2.job_title', 'like', '%' . $request->keyWord . '%')->orWhere('t1.name', 'like', '%' . $request->keyWord . '%');
                }
            })
            ->where(function ($query) use ($request) {
                if (strlen($request->status) > 0) {
                    $query->where('log.status', $request->status);
                }
            })
            ->where('log.status', '!=', 4)
            ->orderBy('log.created_at', 'DESC')
            ->paginate(20);
        //print_r($queries );

        foreach ($relist as $v) {

            if ($v->lang_type == 'en') {
                switch ($v->sex) {
                    case "1":
                        $v->cnsex = 'Man';
                        break;
                    case "2":
                        $v->cnsex = 'Woman';
                        break;
                    default:
                        $v->cnsex = '';
                }
                $v->education = EnCollOption::getOptionName($v->education, 'education');
                $v->homeaddress = EnCollArea::getAreaName($v->homeaddress);
                $v->birthday = birthday($v->birthday);

            } else {
                switch ($v->sex) {
                    case "1":
                        $v->cnsex = '男';
                        break;
                    case "2":
                        $v->cnsex = '女';
                        break;
                    default:
                        $v->cnsex = '';
                }
                $v->education = CollOption::getOptionName($v->education, 'education');
                $v->homeaddress = CollArea::getAreaName($v->homeaddress);
                $v->birthday = birthday($v->birthday);
            }
        }
        $status = $request->status;

        return Style::view('company.resumeMessage', compact('relist', 'status'));

    }

    /**
     * 面试状态设置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function status(Request $request)
    {
        $allow = array(2, 3); //允许的状态码
        if (in_array($request->status, $allow)) {
            $user = auth()->guard('company')->user();
            switch ($request->status) {
                case "2":
                    $msg = '已邀约';
                    break;
                case "3":
                    $msg = '已婉拒';
                    break;
                default:
                    '';
            }
            $input['status'] = $request->status;
            ResumeSend::where('company_uid', $user->uid)->where('id', $request->id)->update($input);
            return response()->json(['status' => $request->status, 'msg' => $msg]);
        }
    }

    /**
     * 删除简历库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        if (is_array($request->selected_id)) {
            $user = auth()->guard('company')->user();
            $input['status'] = 4;//删除
            ResumeSend::where('company_uid', $user->uid)->whereIn('id', $request->selected_id)->update($input);
            return back()->withInput()->with('info', "已删除!");
        }
    }


    /**
     * 企业纳入人才库-显示企业工作列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function toShowCompanyJobList(Request $request)
    {
        $request->only("resumeId");
        $user = auth()->guard('company')->user();
        if(!empty($user)){
            $CompanyJob = CompanyJob::select("id", "job_title", "location1", "location2", "location3", "location4",
                "location5", "salary_above", "salary_below", "updatetime")->with(["personnelIsHaveInsert" => function ($query) {
                $query->select("id", "job_id", "status", "resume_id");
            }])
                ->where("uid", $user->uid)->where("job_status", 1)->get();

            foreach ($CompanyJob as $v) {
                $v->updatetime = substr($v->updatetime, 0, 10);
                if (!empty($v->personnelIsHaveInsert->job_id) && $v->personnelIsHaveInsert->resume_id == $request->resumeId && $v->personnelIsHaveInsert->status != 4) {
                    $v->personnelIsHaveInsert->have = 1;
                }
                //工作地区
                !empty($v->location1) ? $v->location1 = CollArea::getAreaName($v->location1) : $v->location1 = '';
                !empty($v->location2) ? $v->location2 = CollArea::getAreaName($v->location2) : $v->location2 = '';
                !empty($v->location3) ? $v->location3 = CollArea::getAreaName($v->location3) : $v->location3 = '';
                !empty($v->location4) ? $v->location4 = CollArea::getAreaName($v->location4) : $v->location4 = '';
                !empty($v->location5) ? $v->location5 = CollArea::getAreaName($v->location5) : $v->location5 = '';

                $v->location = str_limit($v->location1 . ' ' . $v->location2 . ' ' . $v->location3 . ' ' . $v->location4 . ' ' . $v->location5, 30);
                //薪资
                if ($v->salary_above == 0 and $v->salary_below == 0) {
                    $v->salary_above = '面议';
                } else {
                    $v->salary_above = CollOption::getOptionName($v->salary_above, 'expectedsalary') . '-' . CollOption::getOptionName($v->salary_below, 'expectedsalary') . '元';
                }

            }
            $resumeFavorite = ResumeFavorite::where("uid", $user->uid)->where('resume_id', $request->resumeId)
                ->where('job_id', '!=', '0')->orderBy('updated_at','desc')->first();
//            dd($resumeFavorite);
            return response()->json(['status' => 1, 'jobTitle' => $CompanyJob,'resumeFavorite'=>$resumeFavorite]);
        }

    }

    /**
     * 放入人才库
     * @param Request $request
     */
    public function toFavorite(Request $request)
    {
        $user = auth()->guard('company')->user();
        if (is_array($request->selected_id)) {
            $browseJob = ResumeSend::select('resume_id', 'job_id')->where('company_uid', $user->uid)->whereIn('id', $request->selected_id)->get();
            foreach ($browseJob as $v) {
                $favorite = ResumeFavorite::select('id')->where('uid', $user->uid)->where('status', '!=', 4)->where("resume_id", $v->resume_id)->first();
                if (!empty($favorite->id)) {
                    $favorite->updated_at = date('Y-m-d H:i:s');
                    $favorite->status = 0;
                    $favorite->save();
                } else {
                    $favorite = new ResumeFavorite;
                    $favorite->uid = $user->uid;
                    $favorite->resume_id = $v->resume_id;
                    $favorite->job_id = $v->job_id;
                    $favorite->status = 0;
                    $favorite->save();
                }
            }
            return back()->withInput()->with('info', "已将简历加入人才库!");
        }
    }

    /**
     * 查看企业简历数
     * @param $resumeId
     * @param $companyUid
     * @param $lookStatus
     * @return array
     */
    public function getContact($resumeId, $companyUid, $lookStatus)
    {
        $status = [];
        //企业已登录
        if (!empty($companyUid) and is_numeric($companyUid)) {//登录
            //判断企业是会员，还是充值会员
            $companyUser = CompanyUser::select('viptime', 'vip_resume_number', 'resume_number')->where('uid', $companyUid)->first();

            if (empty($companyUser->viptime) || $this->timediff($companyUser->viptime) < 0) {//不是会员 或 vip时间空或会员时间<0

                //查看简历数是否>0
                if ($companyUser->resume_number > 0) {

                    //查询联系方式
                    $resume = Resume::select('mobile', 'email', 'qq')->where('id', $resumeId)->first();
                    if ($resume) {
                        if ($lookStatus == 0) {//未查看过
                            //减去一份简历
                            CompanyUser::where('uid', $companyUid)->decrement('resume_number');
                            $CompanyBasic = CompanyBasic::select('id')->where('uid', $companyUid)->orderBy('addtime', 'desc')->first();
                            //添加查看记录
                            $resume = Resume::select('uid', 'mobile', 'email', 'qq')->where('id', $resumeId)->first();
                            $input['company_uid'] = $companyUid;
                            $input['personal_uid'] = $resume->uid;
                            $input['resume_id'] = $resumeId;
                            $input['com_id'] = !empty($CompanyBasic) ? $CompanyBasic->id : '';
                            BuyResume::create($input);
                        }
                    }
                    $status = [1, $resume];
                } elseif ($this->timediff($companyUser->viptime) < 0 and $companyUser->resume_number == 0) {//会员时间过期
                    if ($lookStatus == 1) {//过期，但购买了非会员简历,最后一份简历，且已看过
                        $resume = Resume::select('uid', 'mobile', 'email', 'qq')->where('id', $resumeId)->first();
                        $status = [1, $resume];
                    } else {
                        $status = [2];//提示充值
                    }
                } else {
                    $status = [0];
                }

            } elseif ($this->timediff($companyUser->viptime) > 0) {//会员时间减去当前时间，>0表示未过期

                //查看会员期内简历数是否>0
                if ($companyUser->vip_resume_number > 0) {

                    //查询联系方式
                    $resume = Resume::select('mobile', 'email', 'qq')->where('id', $resumeId)->first();
                    if ($resume) {
                        if ($lookStatus == 0) {//未查看过
                            //减去一份简历
                            CompanyUser::where('uid', $companyUid)->decrement('vip_resume_number');
                            $CompanyBasic = CompanyBasic::select('id')->where('uid', $companyUid)->orderBy('addtime', 'desc')->first();
                            //添加查看记录
                            $resume = Resume::select('uid', 'mobile', 'email', 'qq')->where('id', $resumeId)->first();
                            $data['company_uid'] = $companyUid;
                            $data['personal_uid'] = $resume->uid;
                            $data['resume_id'] = $resumeId;
                            $data['com_id'] = !empty($CompanyBasic) ? $CompanyBasic->id : '';
                            BuyResume::create($data);
                        }
                    }
                    $status = [1, $resume];
                } elseif ($companyUser->resume_number > 0) {//会员期内简历用完，购买了非会员简历
                    //查询联系方式
                    $resume = Resume::select('mobile', 'email', 'qq')->where('id', $resumeId)->first();
                    if ($resume) {
                        if ($lookStatus == 0) {//未查看过
                            //减去一份简历
                            CompanyUser::where('uid', $companyUid)->decrement('resume_number');
                            $CompanyBasic = CompanyBasic::select('id')->where('uid', $companyUid)->orderBy('addtime', 'desc')->first();
                            //添加查看记录
                            $resume = Resume::select('uid', 'mobile', 'email', 'qq')->where('id', $resumeId)->first();
                            $input['company_uid'] = $companyUid;
                            $input['personal_uid'] = $resume->uid;
                            $input['resume_id'] = $resumeId;
                            $input['com_id'] = !empty($CompanyBasic) ? $CompanyBasic->id : '';
                            BuyResume::create($input);
                        }
                    }
                    $status = [1, $resume];
                } else {
                    $status = [0];
                }

            } else {//提示注册企业用户无权限并充值
                $status = [0];
            }

            //企业在会员期内收到的简历，可直接查看
            if ($lookStatus == 2) {
                $resume = Resume::select('mobile', 'email', 'qq')->where('id', $resumeId)->first();
                if ($resume) {
                    $status = [1, $resume];
                } else {
                    $status = [0];
                }
            }

            return $status;
        }
    }

    /**
     * 返回简历是否被购买查看
     * @param $uid
     * @param $resumeId
     * @return int
     */
    public function lookResumeStatus($uid, $resumeId)
    {
        if (!empty($uid)) {
            $BuyResume = BuyResume::where('company_uid', $uid)->where('resume_id', $resumeId)->first();
            if ($BuyResume) {
                $lookStatus = 1;//简历被购买查看过
            } else {
                $lookStatus = 0;//简历未被查看过
            }
        } else {
            $lookStatus = 0;//未登录
        }
        return $lookStatus;
    }

    /**
     * 企业请求查看个人简历联系方式
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function personContact(Request $request)
    {
        $request->only('resumeId');
        $user = auth()->guard('company')->user();
        //简历是否被查看
        $lookStatus = $this->lookResumeStatus($user->uid, $request->resumeId);

        if (!empty($user->uid)) {
            $resumeMoneyStatus = $this->getContact($request->resumeId, $user->uid, $lookStatus);
            //0提示充值,1表示有简历数，输出联系方式
            if ($resumeMoneyStatus[0] == 1) {
                $mobile = $resumeMoneyStatus[1]['mobile'];
                $email = $resumeMoneyStatus[1]['email'];
                $qq = $resumeMoneyStatus[1]['qq'];
            } else {
                $mobile = '';
                $email = '';
                $qq = '';
            }

        }
        return response()->json(['status' => $resumeMoneyStatus[0], 'mobile' => $mobile, 'email' => $email, 'qq' => $qq]);
    }

    /**
     * 企业邀请个人面试
     * @return \Illuminate\Http\JsonResponse
     */
    public function inviteInterview()
    {
        $user = auth()->guard('company')->user();
        if (!empty($user->uid)) {
            $CompanyJob = CompanyJob::select("id", "com_id", "job_title")->where('uid', $user->uid)->where('job_status', '1')->get();
            $inviteTitle = [];
            if ($CompanyJob and count($CompanyJob) > 0 and $user->resumeNumber() <= 0) {
                $status = 2;
            } elseif ($CompanyJob and count($CompanyJob) > 0 and $user->resumeNumber() > 0) {
                foreach ($CompanyJob as $k => $v) {
                    //$inviteId[$k] = $v->id;
                    $inviteTitle[] = array(
                        'value' => $v->id,
                        'text' => str_limit($v->job_title, 32)
                    );
                }
                $status = 1;
            } else {
                $status = 3;
            }
            $date = date('Y-m-d 10:00:00');
            $date = date_create($date);
            date_sub($date, date_interval_create_from_date_string("-1 days"));//当前时间加上一天
            $interViewTime = date_format($date, "Y-m-d 10:00:00");
        }

        return response()->json(['status' => $status, 'inviteTitle' => $inviteTitle, 'interViewTime' => $interViewTime]);
    }

    /**
     * 时间差
     * @param $time
     * @return int
     */
    public function timediff($time)
    {
        $timezone = Config::get('app.timezone', 'PRC');
        date_default_timezone_set($timezone);
        $zero1 = strtotime(date("Y-m-d H:i:s", time()));
        $zero2 = strtotime($time);
        $time_c = $zero2 - $zero1;
        return $time_c;
    }
}